<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/8/24
 * Time: 13:11
 */

namespace app\service;


use Redis\Redis;
use think\Db;

class IGeTuiService
{
    private $host = 'http://sdk.open.api.igexin.com/apiex.htm';
    //测试
    private $appkey = '';
    private $appid = '';
    private $mastersecret = '';

    private function init()
    {
        // header("Content-Type: text/html; charset=utf-8");
        $this->appid = config('getui.appid');
        $this->appkey = config('getui.appkey');
        $this->mastersecret = config('getui.mastersecret');
        $this->host = config('getui.host');
    }

    public function __construct()
    {
        $this->init();
        $this->__loader();
    }

    private function __loader()
    {
        require_once(ROOT . '/vendor/getuilaboratory/getui-pushapi-php-client/IGt.Push.php');
        require_once(ROOT . '/vendor/getuilaboratory/getui-pushapi-php-client/igetui/IGt.AppMessage.php');
        require_once(ROOT . '/vendor/getuilaboratory/getui-pushapi-php-client/igetui/IGt.TagMessage.php');
        require_once(ROOT . '/vendor/getuilaboratory/getui-pushapi-php-client/igetui/IGt.APNPayload.php');
        require_once(ROOT . '/vendor/getuilaboratory/getui-pushapi-php-client/igetui/template/IGt.BaseTemplate.php');
        require_once(ROOT . '/vendor/getuilaboratory/getui-pushapi-php-client/IGt.Batch.php');
        require_once(ROOT . '/vendor/getuilaboratory/getui-pushapi-php-client/igetui/utils/AppConditions.php');
        require_once(ROOT . '/vendor/getuilaboratory/getui-pushapi-php-client/igetui/template/notify/IGt.Notify.php');
        require_once(ROOT . '/vendor/getuilaboratory/getui-pushapi-php-client/igetui/IGt.MultiMedia.php');
        require_once(ROOT . '/vendor/getuilaboratory/getui-pushapi-php-client/payload/VOIPPayload.php');
//        require_once ('igetui/template/IGt.RevokeTemplate.php');
//        require_once ('igetui/template/IGt.StartActivityTemplate.php');

    }


    /**
     * @param $code
     * @return mixed
     * @content 查询用户状态
     */
    function getUserStatus($code)
    {
        $redis = new Redis();
        # 通过code查询cid
        $memberInfo = $redis->hGetJson('memberInfo', strtoupper($code));
        $cid = $memberInfo['cid'];
        $igt = new \IGeTui($this->host, $this->appkey, $this->mastersecret);
        $rep = $igt->getClientIdStatus($this->appid, $cid);
        return $rep['result'];
    }

    //服务端推送接口，支持三个接口推送
    //1.PushMessageToSingle接口：支持对单个用户进行推送
    //2.PushMessageToList接口：支持对多个用户进行推送，建议为50个用户
    //3.pushMessageToApp接口：对单个应用下的所有用户进行推送，可根据省份，标签，机型过滤推送
    //单推接口案例
    function pushMessageToSingle($content, $title, $text, $code, $template = 1)
    {
        $redis = new Redis();
        # 通过code查询cid
        $memberInfo = $redis->hGetJson('memberInfo', strtoupper($code));
        $cid = $memberInfo['cid'];
        if (empty($cid) or $cid == 'null') {
            $cid = Db::table('member')->where(array('code' => strtoupper($code)))->field('cid')->find()['cid'];
            if (!empty($cid) and $cid != 'null') {
                $memberInfo['cid'] = $cid;
                $redis->hSetJson('memberInfo', strtoupper($code), $memberInfo);
            }
        }
        if (empty($cid)) {
            return array('status' => false, 'msg' => 'cid为空');
        }
        # 判断用户状态
        $IGeTui = new IGeTuiService();
        $playerStatus = $IGeTui->getUserStatus($code);
        if($playerStatus=='Offline'){
            # 不在线 发送短信
            $smsRedis = $redis->hGet('pushSms'.$title,$code);
            if(empty($smsRedis)) {
                SmsCode::Ysms($memberInfo['phone'], $text.",请前往APP内查看", false);
                $redis->hSet('pushSms'.$title,$code,'YES',1800);
                return array('status'=>true,'msg'=>'短信发送成功');
            }else{
                return array('status'=>false,'msg'=>'三十分钟内不能重复发送');
            }
        }else {
            # 3秒内操作过, 不发送消息
            $operation = Db::table('log_login')->where(array('member_code' => $code))
                ->where("date(create_time) = '" . date('Y-m-d') . "'")
                ->where('(' . time() . '-UNIX_TIMESTAMP(change_time))<=3')
                ->find();
            if (empty($operation)) {
                # 在线发送通知
                $igt = new \IGeTui($this->host, $this->appkey, $this->mastersecret);
                //消息模版：
                // 通知栏消息模板
                if ($template == 1) {
                    $template = $this->IGtLinkTemplate($content, $title, $text);
                } else {
                    // 穿透消息模板
                    $template = $this->IGtTransmissionTemplateDemo($content, $title, $text);
                }
//        dump($template);

                //定义"SingleMessage"
                $message = new \IGtSingleMessage();

                $message->set_isOffline(true);//是否离线
                $message->set_offlineExpireTime(3600 * 12 * 1000);//离线时间
                $message->set_data($template);//设置推送消息类型
                //$message->set_PushNetWorkType(0);//设置是否根据WIFI推送消息，2为4G/3G/2G，1为wifi推送，0为不限制推送
                //接收方
                $target = new \IGtTarget();
                $target->set_appId($this->appid);
                $target->set_clientId($cid);
                //    $target->set_alias(Alias);

                try {
                    $rep = $igt->pushMessageToSingle($message, $target);
                    return $rep;
//            echo("<br><br>");

                } catch (RequestException $e) {
                    $requstId = e . getRequestId();
                    //失败时重发
                    $rep = $igt->pushMessageToSingle($message, $target, $requstId);
                    return $rep;
//            echo("<br><br>");
                }
            }
        }
    }


    //穿透消息模板
    public function IGtTransmissionTemplateDemo($content, $title, $text)
    {
        $template = new \IGtTransmissionTemplate();
        $template->set_appId($this->appid); //应用appid
        $template->set_appkey($this->appkey); //应用appkey
        //透传消息类型
        $template->set_transmissionType(2);
        $payload = [
            'title' => $title,
            'content' => $text,
//            'payload'=>'测试的啦'
        ];
        //透传内容
        $template->set_transmissionContent(json_encode($payload, JSON_UNESCAPED_UNICODE));
        // $template->set_duration(BEGINTIME,ENDTIME); //设置ANDROID客户端在此时间区间内展示消息
        //这是老方法，新方法参见iOS模板说明(PHP)*/
        //$template->set_pushInfo("actionLocKey","badge","message",
        //"sound","payload","locKey","locArgs","launchImage");

        //  APN高级推送
        // $apn = new \IGtAPNPayload();
        // $alertmsg=new \DictionaryAlertMsg();
        // $alertmsg->body="body";
        // $alertmsg->actionLocKey="ActionLockey";
        // $alertmsg->locKey="LocKey";
        // $alertmsg->locArgs=array("locargs");
        // $alertmsg->launchImage="launchimage";
        return $template;
    }

    //通知栏消息 (通知栏显示 点击启动应用)
    function IGtNotificationTemplateDemo($content, $title, $text)
    {
        $template = new \IGtNotificationTemplate();
        $template->set_appId($this->appid); //应用appid
        $template->set_appkey($this->appkey); //应用appkey
        $template->set_transmissionType(1);//透传消息类型
        $template->set_transmissionContent($content);//透传内容
        $template->set_title($title);//通知栏标题
        $template->set_text($text);//通知栏内容
        $template->set_logo("https://meng.childpi.com/static/logo.png");//通知栏logo
        $template->set_isRing(true);//是否响铃
        $template->set_isVibrate(true);//是否震动
        $template->set_isClearable(true);//通知栏是否可清除
        //$template->set_duration(BEGINTIME,ENDTIME); //设置ANDROID客户端在此时间区间内展示消息
        return $template;
    }

    //群推接口案例
    public function pushMessageToApp()
    {
        $igt = new \IGeTui($this->host, $this->appkey, $this->mastersecret);

        $template = $this->IGtNotificationTemplateDemo();
        //个推信息体
        //基于应用消息体
        $message = new \IGtAppMessage();
        $message->set_isOffline(true);
        $message->set_offlineExpireTime(10 * 60 * 1000);//离线时间单位为毫秒，例，两个小时离线为3600*1000*2
        $message->set_data($template);
        //    $message->setPushTime("201808011537");
        $appIdList = array($this->appid);
        $phoneTypeList = array('ANDROID');
        $provinceList = array('上海');
        $tagList = array('中文');
        $age = array("0000", "0010");

        //推送条件
        // $cdt = new \AppConditions();
        // 手机类型
        // $cdt->addCondition(\AppConditions::PHONE_TYPE, $phoneTypeList);
        // 地区
        // $cdt->addCondition(\AppConditions::REGION, $provinceList);
        // 标签
        // $cdt->addCondition(\AppConditions::TAG, $tagList);
        // 年龄？
        // $cdt->addCondition("age", $age);
        // $message->set_conditions($cdt);

        $message->set_appIdList($appIdList);

        $rep = $igt->pushMessageToApp($message);

        var_dump($rep);
        echo("<br><br>");
    }

    //通知栏显示 点击跳转url
    function IGtLinkTemplate($content, $title, $text)
    {
        $template = new \IGtLinkTemplate();
        $template->set_appId($this->appid);//应用appid
        $template->set_appkey($this->appkey);//应用appkey
        //透传消息类型
        $template->set_transmissionType(2);
        $payload = [
            'title' => $title,
            'content' => $text,
//            'payload'=>'测试的啦'
        ];
        //透传内容
        $template->set_transmissionContent(json_encode($payload, JSON_UNESCAPED_UNICODE));
        $template->set_title($title);//通知栏标题
        $template->set_text($text);//通知栏内容
        $template->set_logo("http://wwww.igetui.com/logo.png");//通知栏logo
        $template->set_isRing(true);//是否响铃
        $template->set_isVibrate(true);//是否震动
        $template->set_isClearable(true);//通知栏是否可清除
        $template->set_url("https://www.8a1.top/pages/index/index");//打开连接地址
        //$template->set_duration(BEGINTIME,ENDTIME); //设置ANDROID客户端在此时间区间内展示消息
        return $template;
    }

}